package com.example.yadowiki

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.KeyEvent
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    @SuppressLint("SetJavaScriptEnabled")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        initView()
    }

    override fun onDestroy() {
        super.onDestroy()
        releaseWebView()
    }

    private fun initView() {
        //支持javascript
        webView?.settings?.javaScriptEnabled = true
// 设置可以支持缩放
        webView?.settings?.setSupportZoom(true)
// 设置出现缩放工具
        webView?.settings?.builtInZoomControls = true
//扩大比例的缩放
        webView?.settings?.useWideViewPort = true
//自适应屏幕
        webView?.settings?.loadWithOverviewMode = true
        webView?.settings?.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        webView?.settings?.textZoom = 100//WebView里的字体就不会随系统字体大小设置发生变化了
        webView?.webViewClient = object: WebViewClient(){
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                return false
            }
        }
//        webView?.loadUrl("https://www.baidu.com/")
        webView?.loadUrl("http://wiki.eado.com.cn/")
        webView.setDownloadListener{url, userAgent,contentDisposition,mimeType,contentLength->
            val intent = Intent(Intent.ACTION_VIEW)
            intent.addCategory(Intent.CATEGORY_BROWSABLE);
            intent.setData(Uri.parse(url));
            startActivity(intent);
        }
    }

    private fun releaseWebView(){
        webView?.clearCache(true)
        webView?.webChromeClient = null
        webView?.webViewClient = null
        webView?.stopLoading()
        webView?.settings?.javaScriptEnabled = false
        webView?.clearHistory()
        webView?.removeAllViews()
        try {
            webView?.destroy()
        }catch (ex: Throwable){
            //
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack();//返回上个页面
            return true;
        }
        return super.onKeyDown(keyCode, event)
    }
}
